﻿using MongoDB.Bson;
using MongoDB.Driver;

namespace QPEngine
{
	[ObjectEvent]
	public class DBComponentEvent : ObjectEvent<DBComponent>, IAwake
	{
		public void Awake()
		{
			this.Get().Awake();
		}
	}

	/// <summary>
	/// 连接mongodb
	/// </summary>
	public class DBComponent : Component
	{
		public MongoClient mongoClient;
		public IMongoDatabase database;

		public void Awake()
		{
            DBConfig config = Game.Scene.GetComponent<StartConfigComponent>().StartConfig.GetComponent<DBConfig>();
            string connectionString = config.ConnectionString;
            mongoClient = new MongoClient(connectionString);
            this.database = this.mongoClient.GetDatabase(config.DBName);
            Log.Debug("db connection success!!");
        }

		public IMongoCollection<Entity> GetCollection(string name)
		{
			return this.database.GetCollection<Entity>(name);
		}

        public string Get (string name, BsonDocument documnet)
        {
            var collection = database.GetCollection<BsonDocument>(name);
            return collection.Find(documnet).ToJson();
        }
	}
}